<template>
  <div class="app-container">
    <el-card class="query-card" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item label="用户名" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
            <el-option
              v-for="dict in dict.type.sys_user_sex"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="queryParams.email"
            placeholder="请输入邮箱"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入电话"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="QQ" prop="qqNumber">
          <el-input
            v-model="queryParams.qqNumber"
            placeholder="请输入QQ"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="微信号" prop="weChat">
          <el-input
            v-model="queryParams.weChat"
            placeholder="请输入微信号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="queryParams.userType" placeholder="请选择用户类型" clearable>
            <el-option
              v-for="dict in dict.type.sys_user_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="评论状态" prop="commentStatus">
          <el-select v-model="queryParams.commentStatus" placeholder="请选择评论状态" clearable>
            <el-option
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="资料来源" prop="dataOrigin">
          <el-select v-model="queryParams.dataOrigin" placeholder="请选择资料来源" clearable>
            <el-option
              v-for="dict in dict.type.sys_user_origin"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
<!--        <el-form-item label="用户状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择用户状态" clearable>
            <el-option
              v-for="dict in dict.type.sys_user_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>-->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:baseUser:add']"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            :disabled="single"
            @click="handleUpdate"
            v-hasPermi="['system:baseUser:edit']"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:baseUser:remove']"
          >删除</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:baseUser:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <vxe-table
        :loading="loading"
        resizable
        :row-config="{isHover: true,height: 90}"
        :data="baseUserList"
        @checkbox-all="handleSelectionChange"
        @checkbox-change="handleSelectionChange"
        :class="showSearch ? 'table-container' : 'table-container-full' "
      >
        <vxe-column type="checkbox" width="60" fixed="left" align="center"></vxe-column>
        <vxe-column title="序号" align="center" type="seq" min-width="60"/>
        <vxe-column title="头像" align="center" field="avatar" width="100">
          <template slot-scope="scope">
            <image-preview v-if="scope.row.avatar" :src="scope.row.avatar" :width="50" :height="50"/>
          </template>
        </vxe-column>
        <vxe-column title="背景图片" align="center" field="backUrl" width="100">
          <template slot-scope="scope">
            <image-preview v-if="scope.row.backUrl" :src="scope.row.backUrl" :width="50" :height="50"/>
          </template>
        </vxe-column>
        <vxe-column title="登录名" align="center" field="userCode" width="150" />
        <vxe-column title="用户名" align="center" field="userName" width="150"/>
        <vxe-column title="性别" align="center" field="gender" width="100">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_sex" :value="scope.row.gender"/>
          </template>
        </vxe-column>
        <vxe-column title="昵称" align="center" field="nickName" width="180"/>
        <vxe-column title="邮箱" align="center" field="email" width="180"/>
        <vxe-column title="电话" align="center" field="phone" width="180"/>
        <vxe-column title="QQ" align="center" field="qqNumber" width="180"/>
        <vxe-column title="微信号" align="center" field="weChat" width="180"/>
        <vxe-column title="生日" align="center" field="birthday" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </vxe-column>
        <vxe-column title="用户状态" align="center" field="status" width="150">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_status" :value="scope.row.status"/>
          </template>
        </vxe-column>
        <vxe-column title="资料来源" align="center" field="dataOrigin" width="150">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_origin" :value="scope.row.dataOrigin"/>
          </template>
        </vxe-column>
        <vxe-column title="用户类型" align="center" field="userType" width="150">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_user_type" :value="scope.row.userType"/>
          </template>
        </vxe-column>
        <vxe-column title="评论状态" align="center" field="commentStatus" width="150">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.commentStatus"/>
          </template>
        </vxe-column>
        <vxe-column title="邮件通知状态" align="center" field="startEmailNotification" width="150">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.startEmailNotification"/>
          </template>
        </vxe-column>
        <vxe-column title="介绍" align="center" field="summary" width="180" show-overflow/>
        <vxe-column title="签名" align="center" field="signature" width="180" show-overflow/>
        <vxe-column title="职业" align="center" field="occupation" width="150"/>
        <vxe-column title="备注" align="center" field="remark" width="150" show-overflow/>
        <vxe-column title="密码错误次数" align="center" field="loginErrorCount" width="150"/>
        <vxe-column title="登录次数" align="center" field="loginCount" width="100"/>
        <vxe-column title="最后登录时间" align="center" field="lastLoginTime" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.lastLoginTime, '{y}-{m}-{d}') }}</span>
          </template>
        </vxe-column>
        <vxe-column title="最后登录IP" align="center" field="lastLoginIp" width="150"/>
        <vxe-column title="密码到期时间" align="center" field="expireTime" width="150">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.expireTime, '{y}-{m}-{d}') }}</span>
          </template>
        </vxe-column>
        <vxe-column title="操作" align="center" fixed="right" min-width="220">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['system:baseUser:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-set-up"
              @click="handleResetPwd(scope.row)"
              v-hasPermi="['system:baseUser:edit']"
            >重置密码</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['system:baseUser:remove']"
            >删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改用户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" v-if="open" v-drag-zoom append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="头像" class="avatar-container">
              <image-upload :key="1" :visible.sync="open" @setImageUrl="setImageUrl" :limit="1" :file-size="5" file-path="/system/user-cover" v-model="form.avatar"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="背景图片" class="avatar-container">
              <image-upload :key="2" :visible.sync="open" @setImageUrl="setImageBackUrl" :limit="1" :file-size="5" file-path="/system/user-cover" v-model="form.backUrl"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="登录名" prop="userCode">
              <el-input v-model="form.userCode" placeholder="请输入登录名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="昵称" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入昵称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" prop="password">
              <el-input v-model="form.password" type="password" show-password placeholder="请输入密码" :disabled="form.id !== null"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="row-content">
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别">
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="parseInt(dict.value)"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入电话" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="QQ" prop="qqNumber">
              <el-input v-model="form.qqNumber" placeholder="请输入QQ" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="微信号" prop="weChat">
              <el-input v-model="form.weChat" placeholder="请输入微信号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="介绍" prop="summary">
              <el-input v-model="form.summary" placeholder="请输入介绍" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生日" prop="birthday">
              <el-date-picker clearable
                v-model="form.birthday"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择生日">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签名" prop="signature">
              <el-input v-model="form.signature" placeholder="请输入签名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="userType">
              <el-select v-model="form.userType" placeholder="请选择用户类型">
                <el-option
                  v-for="dict in dict.type.sys_user_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="评论状态" prop="commentStatus">
              <el-select v-model="form.commentStatus" placeholder="请选择评论状态">
                <el-option
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮件通知状态 " prop="startEmailNotification">
              <el-select v-model="form.startEmailNotification" placeholder="请选择邮件通知状态 ">
                <el-option
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="资料来源" prop="dataOrigin">
              <el-select v-model="form.dataOrigin" placeholder="请选择资料来源">
                <el-option
                  v-for="dict in dict.type.sys_user_origin"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="职业" prop="occupation">
              <el-input v-model="form.occupation" placeholder="请输入职业" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择用户状态">
                <el-option
                  v-for="dict in dict.type.sys_user_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" rows="3" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--  重置密码弹框  -->
    <el-dialog title="重置密码" :visible.sync="pwdOpen" v-if="pwdOpen" width="400px" v-drag-zoom append-to-body>
      <el-form ref="pwdForm" size="small" :model="pwdForm" :rules="pwdRules" label-width="80px">
        <el-form-item label="新密码" prop="password">
          <el-input v-model="pwdForm.password" type="password" show-password placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="确认密码" prop="passwordAgain">
          <el-input v-model="pwdForm.passwordAgain" type="password" show-password placeholder="请输入密码" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPwdForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listBaseUser,
  getBaseUser,
  delBaseUser,
  addBaseUser,
  updateBaseUser,
  resetPassword
} from '@/api/system/baseUser'
import resetPwd from '@/views/system/user/profile/resetPwd.vue'

export default {
  name: "BaseUser",
  dicts: ['sys_user_origin', 'sys_yes_no', 'sys_user_type', 'sys_user_sex', 'sys_normal_disable', 'sys_user_status'],
  data() {
    /** 密码正则表达式 */
    const pwdReg = /^(([a-zA-Z]+[0-9]+)|([0-9]+[a-zA-Z]+)|([a-z]+[@#%*$_^&])|([0-9]+[@#%*$_^&]))([a-zA-Z0-9@#%*$_^&]*)$/;
    /** 密码校验 */
    const validatePassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (!pwdReg.test(this.pwdForm.password)) {
          callback(new Error('密码格式错误！'));
        } else if (this.pwdForm.passwordAgain !== '') {
          this.$refs.pwdForm.validateField('passwordAgain');
          callback();
        } else {
          callback();
        }
      }
    };
    /** 密码校验 */
    const validatePasswordAgain = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else {
        if (!pwdReg.test(this.pwdForm.passwordAgain)) {
          callback(new Error('密码格式错误！'));
        } else if (value !== this.pwdForm.password) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户管理表格数据
      baseUserList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        gender: null,
        email: null,
        phone: null,
        qqNumber: null,
        weChat: null,
        userType: null,
        commentStatus: null,
        dataOrigin: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 重置密码表达参数
      pwdForm: {
        id:  null,
        password: '',
        passwordAgain: ''
      },
      pwdRules: {
        password: [
          { validator: validatePassword, trigger: 'blur' }
        ],
        passwordAgain: [
          { validator: validatePasswordAgain, trigger: 'blur' }
        ]
      },
      pwdOpen: false,
      // 用户初始密码
      initPassword: '',
    };
  },
  created() {
    this.getList();
    this.getConfigKey("sys.user.initPassword").then(response => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询用户管理列表 */
    getList() {
      this.loading = true;
      listBaseUser(this.queryParams).then(response => {
        this.baseUserList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.pwdOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userCode: null,
        userName: null,
        password: null,
        gender: null,
        avatar: null,
        nickName: null,
        birthday: null,
        email: null,
        phone: null,
        qqNumber: null,
        weChat: null,
        summary: null,
        signature: null,
        orderNo: null,
        loginErrorCount: null,
        loginCount: null,
        lastLoginTime: null,
        lastLoginIp: null,
        expireTime: null,
        userType: null,
        validCode: null,
        commentStatus: null,
        ipSource: null,
        browser: null,
        oprationSystem: null,
        startEmailNotification: null,
        loadingValid: null,
        dataOrigin: null,
        originUid: null,
        occupation: null,
        status: null,
        remark: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        delFlag: null
      };
      this.pwdForm = {
        id:  null,
        password: '',
        passwordAgain: ''
      }
      this.resetForm("form");
      this.resetForm("pwdForm");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(row) {
      this.ids = row.records.map(item => item.id)
      this.single = row.records.length!==1
      this.multiple = !row.records.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.password = this.initPassword;
      this.open = true;
      this.title = "添加用户管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getBaseUser(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            this.form.password = '';
            updateBaseUser(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBaseUser(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除用户管理编号为"' + ids + '"的数据项？').then(function() {
        return delBaseUser(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/baseUser/export', {
        ...this.queryParams
      }, `baseUser_${new Date().getTime()}.xlsx`)
    },
    /** 回写头像图片url */
    setImageUrl(url) {
      this.$set(this.form, 'avatar', url);
    },
    /** 回写背景图片url */
    setImageBackUrl(url) {
      this.$set(this.form, 'backUrl', url);
    },
    handleResetPwd(row) {
      this.pwdOpen = true;
      this.$set(this.pwdForm, "id", row.id);
    },
    /** 重置密码提交 */
    submitPwdForm() {
      this.$refs['pwdForm'].validate((valid) => {
        if (valid) {
          resetPassword(this.pwdForm).then(response => {
            this.$modal.msgSuccess("密码重置成功");
            this.pwdOpen = false;
            this.getList();
          });
        } else {
          return false;
        }
      })
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .table-container {
  .vxe-table {
    height: calc(100vh - 364.5px);
  }
  .vxe-table--body-wrapper {
    height: calc(100vh - 408.5px);
  }
  .fixed-left--wrapper,
  .fixed-right--wrapper {
    height: calc(100vh - 417.5px);
  }
}
::v-deep .el-date-editor {
  width: 100% !important;
}
</style>
